package t10086.WorkThread;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer implements Runnable {
    private final ServerSocket serverSocket;
    public SocketServer(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }
    @Override
    public void run() {
        while (true) {
            try {
                // 等待客户端连接
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected: " + clientSocket.getInetAddress()+":"+clientSocket.getPort());

                // 这里可以启动新的线程来处理客户端请求
                ThreadPoolManager.submitTask(new ClientHandler(clientSocket));
            } catch (IOException e) {
                // 捕获连接异常后打印日志，但不中断循环
                if (serverSocket.isClosed()) {
                    System.out.println("Server socket is closed. Exiting...");
                    break;  // 捕获到异常后再次检查并退出循环
                }

                System.err.println("Error accepting client connection: " + e.getMessage());
            }
        }
    }

}
